import { AfterContentInit, Component, ComponentFactoryResolver, ComponentRef, OnDestroy, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { ButtonComponent } from 'ng-devui';
import Quill from './editor/better-quill';
import { TOOLBAR_CONFIG } from './editor/conf';
import {
  card, divider, emoji, file, tag,
  dragon, snake,
  pie, mind,
  pdf,
} from './editor/handlers';
import PdfLib from './shared/pdf-lib';

const Delta = Quill.import('delta');
const PDF_PATH = 'assets/docs/编写可读代码的艺术.pdf';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, AfterContentInit, OnDestroy {
  title = 'ng-demo-quill';
  pdfLib;
  currentPage = 1;
  quill;

  @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
  compRef: ComponentRef<any>;

  constructor(
    private resolver: ComponentFactoryResolver,
  ) { }

  ngOnInit(): void {
    // const pie = new Pie('.chart-pie');
    // console.log('pie:', pie);

    // const jsmind = new Mind(document.querySelector('.jsmind-container'));

    const quill = new Quill('#editor', {
      theme: 'snow',
      modules: {
        toolbar: {
          container: TOOLBAR_CONFIG,
          handlers: {
            card, divider, emoji, file, tag,
            dragon, snake,
            pie, mind, pdf,
          },
        }
      },
    });
    this.quill = quill;

    /*
    const quill = new Quill('#editor', {
      // bounds: '.layout-container',
      theme: 'snow', // bubble
      // scrollingContainer: '.layout-container',
      // formats: [],
      // placeholder: '输入评论...',
      modules: {
        // toolbar: [
        //   [{ header: [1, 2, 3, false] }],
        //   ['bold', 'italic', 'underline', 'link'],
        //   [{ list: 'ordered'}, { list: 'bullet' }],
        //   ['clean'],
        //   ['image']
        // ]

        // toolbar: [
        //   ['bold'],
        //   ['italic'],
        //   ['underline'],
        //   [{ header: 1 }],
        //   [{ header: 2 }],
        //   ['blockquote'],
        //   ['code-block'],
        //   ['code'],
        //   [{ list: 'bullet' }],
        //   [{ list: 'ordered'}],
        //   ['link'],
        //   ['image'],
        // ]

        toolbar: '#toolbar'
      }
    });
    this.quill = quill;
    console.log('quill:', quill);
    */

    // Quill Module
    // const clipboardModule = this.quill.getModule('clipboard');
    // console.log('clipboardModule1:', clipboardModule, clipboardModule.matchers);

    // this.quill.clipboard.addMatcher('span[class="tag-container"]', function(node, delta) {
    //   console.log('tag1 node, delta:', node, delta);
    //   return delta;
    // });

    // this.quill.clipboard.addMatcher('span', function(node, delta) {
    //   console.log('span2 node, delta:', node, delta);
    //   return delta;
    // });

    // this.quill.clipboard.addMatcher('strong', function(node, delta) {
    //   console.log('strong3 node, delta:', node, delta);
    //   return delta;
    // });

    // this.quill.clipboard.addMatcher('div', function(node, delta) {
    //   console.log('div node, delta:', node, delta);
    //   return delta;
    // });

    // this.quill.clipboard.addMatcher('canvas', function(node, delta) {
    //   console.log('canvas node, delta:', node, delta);
    //   return delta;
    // });
    // console.log('this.quill.clipboard:', this.quill.clipboard);

    // this.quill.clipboard.onPaste(this.quill.getSelection(), {
    //   text: 'kagol'
    // });
    // this.quill.clipboard.onCapturePaste((res) => {
    //   console.log('res:', res);
    // });

    // pdf
    // const canvas: any = document.getElementById('canvas-pdf');
    // const viewer: any = document.getElementById('pdf-page-container');
    // const pdfLib = new PdfLib(canvas, {
    //   docPath: PDF_PATH,
    // });
    // this.pdfLib = pdfLib;
    // pdfLib.renderPage(this.currentPage);

    // pdfLib.renderViewer(this.currentPage);
  }

  ngAfterContentInit(): void {
    // this.loadComponent();
  }

  ngOnDestroy(): void {
    if (this.compRef) {
      this.compRef.destroy();
    }
  }

  format(): void {
    const range = this.quill.getSelection();
    const value = {
      background: '#ffe8e6', // #e4f7d2 #e9e9e9 #fff8bd
      color: '#820014', // #135200 #595959 #614700
    };
    console.log('this.quill:', this.quill);
    this.quill.insertText(range?.index || 0, 'Test', { tag: value });
    console.log('this.quill contents:', this.quill.getContents());
  }

  updateContents(): void {
    this.quill.updateContents(new Delta({
      ops: [
        {
          retain: 6
        },
        {
          insert: 'Quill',
          attributes: {
            tag: {
              background: '#fff8bd',
              color: '#614700',
            }
          }
        }
      ]
    }));
  }

  loadComponent(type): void {
    this.container.clear();
    const factory = this.resolver.resolveComponentFactory(ButtonComponent);
    this.compRef = this.container.createComponent(factory);
    console.log('this.compRef.instance:', this.compRef.instance);
    this.compRef.instance.bsStyle = type;
    this.compRef.instance.icon = 'icon-add';
    this.compRef.instance.btnClick.subscribe((event) => {
      console.log('click:', event);
    });
    // this.compRef.instance.buttonContent.nativeElement.innerHTML = 'OK';
    console.log('this.compRef.instance:', this.compRef.instance);
  }

  prevPage(): void {
    this.currentPage--;
    this.pdfLib.renderPage(this.currentPage);
  }

  nextPage(): void {
    this.currentPage++;
    this.pdfLib.renderPage(this.currentPage);
  }

  deleteText(): void {
    // console.log('this.quill:', this.quill);
    // const range = this.quill.getSelection();
    // console.log('range:', range);

    // 内容
    // deleteText()
    // if (range) {
    //   console.log('range.index:', range.index);
    //   console.log('range.length:', range.length);
    //   this.quill.deleteText(range.index, range.length);
    // } else {
    //   this.quill.deleteText(0, 1);
    // }
    // this.quill.deleteText(0, this.quill.getLength());
    // const { index, length } = this.quill.getSelection();
    // this.quill.deleteText(index, length);

    // removeFormat()
    // this.quill.removeFormat(0, 1);
    // this.quill.removeFormat(0, this.quill.getLength());
    // const { index, length } = this.quill.getSelection();
    // this.quill.removeFormat(index, length);

    // getContents()
    // const contents = this.quill.getContents(index, length);
    // console.log('contents:', contents, JSON.stringify(contents));

    /*
    // 查找替换
    const text = this.quill.getText();
    console.log('text:', text);

    // const search = text.search(/Quill/g);
    // console.log('search:', search);

    const str = 'Quill';
    const reg = new RegExp(str, 'g');
    const length = str.length;
    // const match = text.match(reg);
    // console.log('match:', match);

    let match;
    while ((match = reg.exec(this.quill.getText())) !== null) {
      console.log('match 2:', match, match.index);

      // 删除
      // this.quill.deleteText(match.index, length);

      // 高亮
      // this.quill.formatText(match.index, length, 'background', '#ef0fff'); // pink #ef0fff yellow #fffec8

      // 增加超链接
      // this.quill.formatText(match.index, length, 'link', 'https://devui.design/');

      // 替换
      this.quill.deleteText(match.index, length);
      this.quill.insertText(match.index, 'DevUI');
      // this.quill.formatText(match.index, length, 'link', 'https://devui.design/');
    }

    // const newText = text.replace(/Quill/g, 'DevUI');
    // console.log('newText:', newText);
    // this.quill.setText(newText);
    */

    // const contents = {
    //   ops: [
    //     { insert: '删除内容' },
    //     { attributes: { header: 2 }, insert: '\n' },
    //     { insert: '先看' },
    //     { attributes: { code: true }, insert: '删' },
    //     { insert: '的部分，通过' },
    //     { attributes: { code: true }, insert: 'deleteText()' },
    //     { insert: '方法实现，该方法主要有两个入参：\nindex 从哪儿删除' },
    //     { attributes: { list: 'bullet' }, insert: '\n' },
    //     { insert: 'length 删除多少内容' },
    //     { attributes: { list: 'bullet' }, insert: '\n' },
    //     { insert: '比如我想把下面的' },
    //     { attributes: { code: true }, insert: 'Hello ' },
    //     { insert: '删除：\nthis.quill.deleteText(0, 6);' },
    //     { attributes: { 'code-block': true }, insert: '\n' },
    //     { insert: '\n' }
    //   ]
    // };

    // getLength()
    // const length = this.quill.getLength();
    // console.log('length:', length);

    // getText()
    // const text = this.quill.getText();
    // console.log('text:', text);
    // console.log('length:', text.length, this.quill.getLength());
    // console.log('selected text:', this.quill.getText(index, length));
    // console.log('selected contents:', this.quill.getContents(index, length));
    // console.log('getFormat:', this.quill.getFormat(index, length));

    // insertEmbed()
    // this.quill.insertEmbed(3, 'image',
    //   'https://user-gold-cdn.xitu.io/2020/1/23/16fd033e94959e97?imageView2/1/w/180/h/180/q/85/interlace/1'
    // );

    // insertText()
    // this.quill.insertText(0, 'DevUI', 'bold', true);
    // this.quill.insertText(52, 'DevUI 是一款面向企业中后台产品的开源前端解决方案');
    // const range = this.quill.getSelection();
    // if (range) {
    //   this.quill.insertText(range.index, 'DevUI', 'link', 'https://devui.design/');
    // }
    // console.log(this.quill.getText(index, length).length);

    // setContents()
    // this.quill.setContents(new Delta({
    //   ops: [
    //     {
    //       insert: 'DevUI',
    //       attributes: { bold: true }
    //     },
    //     {
    //       insert: {
    //         image: 'https://user-gold-cdn.xitu.io/2020/1/23/16fd033e94959e97?imageView2/1/w/180/h/180/q/85/interlace/1'
    //       }
    //     },
    //     {
    //       insert: {
    //         dragon: { id: 'canvas-dragon' }
    //       }
    //     }
    //   ]
    // }));
    // this.quill.setContents([
    //   { insert: { snake: { id: 'snake' } } }
    // ]);

    // setText()
    // this.quill.setText('');
    // this.quill.setText('DevUI is excellent');

    // dangerouslyPasteHTML()
    // this.quill.clipboard.dangerouslyPasteHTML('DevUI is <span style="color: red">excellent</span>');
    // this.quill.clipboard.dangerouslyPasteHTML(0, 'DevUI is <span style="color: red">excellent</span>');

    // updateContents()
    // this.quill.updateContents(new Delta({
    //   ops: [
    //     { retain: 10 },
    //     { delete: 10 },
    //     { insert: 'DevUI is excellent' }
    //   ]
    // }));

    // const { index, length } = this.quill.getSelection();
    // this.quill.deleteText(index, length);
    // this.quill.insertText(index, 'DevUI', 'link', 'https://devui.design/');

    // const { index, length } = this.quill.getSelection();
    // this.quill.updateContents([
    //   { retain: index },
    //   { delete: length },
    //   { insert: 'DevUI', attributes: { link: 'https://devui.design/' } }
    // ]);

    // 选区
    // getBounds
    // const bounds = this.quill.getBounds(0, 3);
    // console.log('bounds:', bounds);
    // console.log('bounds 2:', this.quill.getText(2, 10), this.quill.getBounds(2, 10));
    // console.log('bounds 20:', this.quill.getText(28, 2), this.quill.getBounds(28, 2));

    // getSelection
    // const selection = this.quill.getSelection();
    // console.log('selection:', selection);

    // setSelection
    // this.quill.setSelection(3, 3);
    // console.log('after selection:', this.quill.getSelection());

    // this.quill.format('color', 'pink');
    // this.quill.formatText(10, 10, 'color', 'pink');
    this.quill.formatLine(0, 1, 'list', 'ordered');
  }
}
